import {defineStore} from "pinia";
import {OperationPageApi} from "../api/OperationPageApi.js";
import {FMessage} from '@fesjs/fes-design';

export const useOperationPageStore = defineStore('useOperationPageStore', {
    state: () => ({
        leftTreeData: [],
        inputPlaceHolder: "",
        inputValue: "",
        actionName: "",
        actionType: "",
        resultValue: "",
        running: false,
        executeButtonDisabled: false,
        disableResetButton: false,
        disableCommandInput: false,
        rowsCount: 0,
        executeRowsCount: 0,
        resultSplitRow: false,
        showHelpInputContent: false,
        subActionList: [],
        _subActionContent: [],
        _subActionList: [],
        currentSelectSubActionParamList: [],
        token: "",
        subActionSelectValue: null,
        stringSubActionList: [],
        stringSubActionCurrentSelect: null
    }),
    actions: {
        async operateMenus() {
            this.leftTreeData = await OperationPageApi.operateMenus()
        },
        async menuSelect(value) {

            if (this.running) {
                FMessage.error("执行中不能切换")
            } else {
                if (value.node.isLeaf) {
                    this.inputPlaceHolder = value.node.origin.param.tips;
                    this.actionName = value.node.origin.param.actionName;
                    this.actionType = value.node.origin.param.actionType;
                    this._subActionContent = value.node.origin.subActionContent;
                    this._subActionList = value.node.origin.subActionList;
                    this.resultValue = "";
                    this.inputValue = "";
                    this.stringSubActionCurrentSelect ="";
                    this.stringSubActionList =[];

                    if (value.node.origin.subActionContent && value.node.origin.subActionContent.length > 0) {
                        this.stringSubActionList = [];
                        value.node.origin.subActionContent.map((c, index) => {
                            this.stringSubActionList.push({value: index, label: c.stringParamLayout})
                            if(index === 0){
                                this.stringSubActionCurrentSelect = c.stringParamLayout;
                            }
                        })

                    }
                }
            }
        },

        stringSubActionSelectHandler(value) {
            console.log(value);
            this.stringSubActionCurrentSelect = this.stringSubActionList[value].label;
            this.inputPlaceHolder = this.stringSubActionList[value].label;
        },

        selectSubAction(index) {
            if (this._subActionContent != null && this._subActionContent.length > 0) {
                this.currentSelectSubActionParamList = this._subActionContent[index].operatorParamList.map(item => {

                    if (item.values && item.values.length === 1) {
                        return {...item, value: item.values[0].value}
                    } else {
                        return {...item, value: null}
                    }
                });
            } else {
                this.currentSelectSubActionParamList = [];
            }
        },

        reset() {
            this.inputValue = "";
            this.resultValue = "";
            this.executeButtonDisabled = false;
            this.disableCommandInput = false;
            this.rowsCount = 0;
            this.executeRowsCount = 0;
        },
        inputHandle(value) {
            let rowsCount = value.split(/\r?\n/).length;
            this.executeButtonDisabled = rowsCount >= 2000;
            this.rowsCount = rowsCount;
            this.executeRowsCount = 0;
        },

        handlePaste(event) {
            event.preventDefault();
            const pasteText = event.clipboardData.getData('text/plain');
            const cleanedText = pasteText.trim();
            document.execCommand('insertText', false, cleanedText);

        },
        async run() {
            if (this.actionName == null || this.actionName === "") {
                FMessage.error("请选择要执行的操作")
                return
            }
            if (this.inputValue == null || this.inputValue === "") {
                FMessage.error("请输入要执行的命令参数")
                return
            }

            this.running = true;
            this.disableResetButton = true;
            this.disableCommandInput = true;

            if (this.actionType === "single") {
                const result = await OperationPageApi.runOperation(this.actionName, this.inputValue.trim())
                console.log(result)

                let isJson = this.isJSON(result);
                if (isJson) {
                    let jsonObject = JSON.parse(result);
                    this.resultValue = JSON.stringify(jsonObject, null, 4)
                } else {
                    this.resultValue = result;
                }

            } else if (this.actionType === "batch") {

                const itemList = this.inputValue.split(/\r?\n/);


                for (const item of itemList) {
                    const result = await OperationPageApi.runOperation(this.actionName, item.trim())
                    let isJson = this.isJSON(result);
                    if (isJson) {
                        let jsonObject = JSON.parse(result);
                        this.resultValue += JSON.stringify(jsonObject, null, 4) + "\n";
                    } else {

                        if (this.resultSplitRow) {

                            if (result != null && result !== "") {

                                let splitResultList = result.split(";");
                                for (const spline of splitResultList) {
                                    if (spline == null || spline.trim() === '') {
                                        continue;
                                    }
                                    this.resultValue += spline.trim() + "\n";

                                }
                            }

                        } else {
                            this.resultValue += result + "\n";
                        }
                    }
                    this.executeRowsCount++;


                }
            }

            this.running = false;
            this.disableResetButton = false;
            this.disableCommandInput = false;

        },

        sleep(ms) {
            return new Promise(r => setTimeout(r, ms));
        },


        isJSON(str) {
            try {
                var obj = JSON.parse(str);
                if (obj && typeof obj === "object") {
                    return true;
                }
            } catch (e) {
            }
            return false;
        },

        exportResult() {
            if (!this.resultValue) {
                FMessage.error("没有可导出的内容");
                return;
            }
            const BOM = '\uFEFF';

            let realResult = BOM + this.resultValue;

            const blob = new Blob([realResult], {type: 'text/plain'});
            const url = URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url;
            a.download = `导出结果_${new Date().toISOString().slice(0, 10)}.txt`;
            document.body.appendChild(a);
            a.click();
            document.body.removeChild(a);
            URL.revokeObjectURL(url);

            FMessage.success("导出成功");
        },
        helpInput() {
            if (this.actionName == null || this.actionName === "") {
                FMessage.error("请选择要执行的操作")
                return
            }
            this.showHelpInputContent = true;

        },
        closeHelpInputDrawer() {
            this.subActionList = [];
            this.currentSelectSubActionParamList = [];
            this.subActionSelectValue = null;
        },
        openHelpInputDrawer() {
            if (this._subActionList && this._subActionList.length > 0) {
                this._subActionList.forEach((item, index) => {
                    this.subActionList.push({index: index, item: item});
                })
            }
        },
        addToExecuteTextbox() {

            if (this.inputValue == null || this.inputValue === '') {
                this.inputValue = this.joinParam();
            } else {
                this.inputValue = this.inputValue + "\n" + this.joinParam();
            }
        },
        joinParam() {
            if (this.currentSelectSubActionParamList) {
                let str = this.currentSelectSubActionParamList.map(p => p.value).join(":");
                return this.token + ":" + str
            }
            return "";
        }
    }
})

